<template>
  <div>
    <el-alert
      title="注意：只允许为第三级分类设置相关参数"
      type="warning"
      show-icon
    >
    </el-alert>
    <span>选择商品分类: </span>
    <el-cascader
      v-model="pid"
      :options="categories"
      :props="{ value: 'cat_id', label: 'cat_name', expandTrigger: 'hover' }"
      @change="getAttributeList"
    ></el-cascader>
    <el-tabs v-model="activeName" @tab-click="getAttributeList">
      <el-tab-pane
        v-for="(item, key) in tabs"
        :key="key"
        :label="item.title1 + item.title"
        :name="key"
      ></el-tab-pane>
    </el-tabs>
    <el-button
      type="primary"
      @click="
        model = {};
        $refs.d.show();
      "
      :disabled="!catId"
    >
      添加{{ activeTab.title }}
    </el-button>
    <!-- 表格 -->
    <Table 
    rowKey="attr_id"
     :cols="cols" 
     :data="list" 

     :loading="queryLoading">
      <!-- 标签 -->
              <template v-slot:expand="{row}">
                    <el-tag
                    :key="index"
                    v-for="(tag,index) in row.tags"
                    closable
                    @close="deleteTag(row,index)">
                    {{tag}}
                    </el-tag>
                    <el-input
                    class="input"
                    autofocus
                    @blur="updateAttrValues(row)"
                    @keyup.enter.native="updateAttrValues(row)"
                    v-model="row.value"
                    v-if="row.visible"
                    :ref="'input'+row.attr_id"
                    size="small"
                    >
                    </el-input>
                    <el-button
                      v-else
                      size="small" 
                      @click="show(row)"
                      >+ New Tag</el-button>

                  </template>
                  <template v-slot:action="{row}">
                       <el-button
                        class="el-icon-edit" 
                        type="primary" size="mini" 
                        @click="
                        model={...row};
                        $refs.d.show()
                        " >编辑</el-button>
                       <el-button
                        class="el-icon-delete-solid" 
                        type="danger" 
                        size="mini"
                        @click="delAttribute(row)" 
                        >删除</el-button>
                  </template>
    </Table>
    <!-- 添加修改 -->
    <MyDialog
      :title="title + activeTab.title1 + activeTab.title"
      ref="d"
      lw="80px"
      @confirm="confirm"
    >
      <MyForm ref="from" v-model="model" :opts="opts" width="100px"> </MyForm>
    </MyDialog>
  </div>
</template>

<script>
import {
  getAttributes,
  getCategories,
  addAttributes,
  updateAttributes,
  deleteAttributes,
} from "api/goods";
import Table from "../../../components/Table.vue";
import MyDialog from "../../../components/Dialog.vue";
import MyForm from "../../../components/Form.vue";
export default {
  name: "params",

  components: { Table, MyDialog, MyForm },
  data() {
    return {
  
      //分类数据
      categories: [],
      //分类id
      paramsId: [],
      model: {},
      //激活的标签页
      activeName: "many",
      tabs: {
        many: {
          title: "参数",
          title1: "动态",
        },
        only: {
          title: "属性",
          title1: "静态",
        },
      },
    };
  },
  created() {
    const pid = this.pid;
    this.getCateogryList();
  },
  methods: {
       /**
             * 删除标签
             */
            async deleteTag(row,index){
               try {
                   row.tags.splice(index,1);
                   row.attr_vals=row.tags.join(" ");
                   await updateAttributes(this.catId,row);
                   this.$message.success("删除成功");
                   this.getAttributeList();
               } catch (error) {}
            },
            /**
             * 更新属性的value值
             */
            async updateAttrValues(row){
                if(!row.value.trim()){
                    return (row.visible=false);
                }
               try {
                   row.attr_vals=row.tags.join(" ")+" "+row.value;
                   await updateAttributes(this.catId,row);
                   this.$message.success("添加成功");
                   this.getAttributeList();
                   row.value="";
                   row.visible=false;
               } catch (error) {
                
               }
            },
            /**
             * 显示输入框
             */
            show(row){
               row.visible=true;
               this.$nextTick(()=>{
                  this.$refs['input'+row.attr_id].focus();
               });
            },
            /**
             * 删除属性
             */
            async delAttribute({attr_id}){
                let res;
               try {
               
                 await deleteAttributes(this.catId,attr_id);
                 this.$message.success('删除成功');
                 this.getAttributeList()
               } catch (error) {}
               res&&res();
            },
    //添加修改
    async confirm() {
      const d = this.$refs.d;
      try {
        d.start();
        await (this.model.attr_id ? updateAttributes : addAttributes)(
          this.catId,
          {
            ...this.model,
            attr_sel: this.activeName,
          }
        );
        this.$message.success(this.title + "成功");
        this.getAttributeList();
        d.hide();
      } catch (error) {}
      d.stop();
    },
    //获取分类参数
    async getAttributeList() {
      try {
        if (!this.catId) {
          return this.list.splice(0, Infinity);
        }
        this.queryLoading = true;
         const list = await getAttributes(this.catId, this.activeName);
        list.forEach((item) => {
          item.tags = item.attr_vals.split(" ").filter((c) => c);
          item.value = "";
          item.visible = false;
        });
        this.list=list
      } catch (error) {
        console.log(error);
      }
      this.queryLoading = false;
    },
    /**
     * 获取分类列表
     */
    async getCateogryList() {
      try {
        this.categories = await getCategories();
      } catch (error) {}
    },
  },
  computed: {
    //标题
    title() {
      return this.model.attr_id ? "修改" : "添加";
    },
    //表单配置项
    opts() {
      return {
        attr_name: {
          title: this.activeTab.title1 + this.activeTab.title,
          required: true,
          max: 20,
        },
      };
    },
    //被激活的页签名称
    activeTab() {
      return this.tabs[this.activeName];
    },
    //属性id
    pid: {
      set(value) {
        this.paramsId = value.length < 3 ? [] : value;
      },
      get() {
        return this.paramsId;
      },
    },
    //分类id
    catId() {
      return this.paramsId.length < 3 ? undefined : this.paramsId.slice(-1)[0];
    },
    //表头
    cols() {
      return [
        {
          type: "expand",
          slot: "expand",
        },
        {
          title: "#",
          type: "index",
        },
        {
          title: this.activeTab.title + "名称",
          name: "attr_name",
        },
        {
          title: "操作",
          slot: "action",
          align: "center",
          width: 300,
        },
      ];
    },
  },
};
</script>

<style lang="scss" scoped>
.el-alert {
  margin-bottom: 10px;
}
.input {
  width: 100px;
}
</style>